var pomelo = window.pomelo;

var host = '127.0.0.1', gatePort = 3014, connPort = 3050;

var params = location.search.split('?')[1].split('_');
var gameId = params[0] || 1,
    playerId = params[1] || 1004,
    token = params[2] || 'test';

document.title = '百家乐 ' + playerId;

var msg3 = [];  // 用来做 currInfo 的容器

var router = {
    enterGame: 'connector.entryHandler.enterGame',
    bid: 'bjl.gameHandler.bid',
    applyBanker: 'bjl.gameHandler.applyBanker',
    exitGame: 'bjl.gameHandler.exiGame'
};

var events = {
    onPlayerEnter: 'onPlayerEnter',
    onPlayerLeave: 'onPlayerLeave',
    onKick: 'onKick',

    onGameXiaZhu: 'onGameXiaZhu',
    onGameKaiPai: 'onGameKaiPai',
    onGameFree: 'onGameFree',
    onGameStart: 'onGameStart',
    onGameBid: 'onGameBid',
    onGameOver: 'onGameOver',
    onCalcResult: 'onCalcResult',
    onChat: 'onChat',
    onCancelBanker: 'onCancelBanker',
    onApplyBanker: 'onApplyBanker',
    onCutInBanker: 'onCutInBanker',
    onSetBanker: 'onSetBanker'
};

var gameOperate = new Vue({
    el: '#gameOperate',
    data: {
        gameId: gameId,
        playerId: playerId,
        roomData: {},
        bidNum: 1,
        bidPos: 8,
        rid: 1,
        msgs: [],
        bankerInfo: '',
        currInfo: ''
    },
    methods: {
        clearMsgs: function () {
            this.msgs = [];
        },
        enterGame: function (cb) {
            var self = this;
            console.log('enterGame');
            var playerId = self.playerId, gameId = this.gameId;
            // this.msgs.push('进入游戏：' + this.gameId);
            pomelo.init(
                {
                    host: '127.0.0.1',
                    port: connPort,
                    log: true
                },
                function () {
                    var route = router.enterGame;
                    pomelo.request(
                        route,
                        {
                            playerId,
                            token,
                            gameId
                        },
                        function (data) {
                            if (data.err) {
                                log('用户进入游戏失败：', data.err);
                                self.addMsg('返回消息：游戏' + self.gameId + '：用户' + playerId + '进入游戏失败！err: ' + data.err);
                            }
                            else {
                                log('用户进入游戏正常！');
                                if (typeof cb === 'function') {
                                    cb();
                                }
                                self.addMsg('游戏' + gameId + '：用户' + playerId + '进入游戏！');

                                self.roomData = {};

                                log('playerList: ', data.playerList);
                                for (let player of data.playerList) {
                                    let playerId = player.playerId;
                                    self.roomData[playerId] = player;
                                }
                                log('roomData: ', self.roomData);

                                if (data.bankerData.bankerId) {
                                    self.bankerId = data.bankerData.bankerId;
                                    self.bankerInfo = '庄:' + self.bankerId + ' coin: ' + self.roomData[self.bankerId].coin;
                                }
                            }
                        });
                });
        },
        leaveGame: function () {
            log('leaveGame');
            var self = this;
            self.addMsg('返回消息：游戏' + self.gameId + '：用户' + playerId + '退出游戏！');
            this.roomData = {};
            pomelo.disconnect();
        },
        applyBanker: function () {
            log('下注！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid,
            route = router.applyBanker;
            var msg = {
                playerId,
                roomId: rid
            };
            pomelo.request(
                route,
                msg,
                function (data) {
                    log('用户申请上庄：', data);
                    if (data.err) {
                        self.addMsg('返回消息：游戏' + gameId + '：用户' + playerId + '上庄失败！err: ' + data.err);
                    }
                    else {
                        log('%s 上庄成功！', playerId);
                        self.addMsg('返回消息：游戏' + gameId + '：用户' + playerId + '上庄成功！');
                    }
                });
        },
        bid: function () {
            log('下注！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, route = router.bid, bidNum = this.bidNum || 1.1, pos = this.bidPos || 0;
            var msg = {};
            msg[pos] = parseInt(bidNum);
            pomelo.request(
                route,
                msg,
                function (data) {
                    log('用户下注：', data);
                    if (data.err) {
                        self.addMsg('返回消息：游戏' + gameId + '：用户' + playerId + '下注失败！err: ' + data.err);
                    }
                });
        },
        exitGame: function () {
            var msg = { exi: 1, stop: true }, route = router.exitGame;
            pomelo.request(
                route,
                msg,
                function (data) {
                    log('停止游戏：', data);
                    // if (data.err) {
                    //     self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '下注失败！err: ' + data.err);
                    // }
                });
        },
        addMsg: function (msg) {
            var time = new Date().toLocaleString();

            this.msgs.push({ time, msg });
            while (this.msgs.length > 8) {
                // log('信息量太大了！', this.msgs);
                this.msgs.shift();
            }
            // return;

            // msg = time + ' : ' + msg;
            // // log(new Date().toLocaleString() + ' : ');
            // msg3.push(msg);
            // while (msg3.length > 8) {
            //     msg3.shift();
            // }
            // // log(msg3);
            // this.currInfo = msg3.join('<br />');
        }
    }
});


pomelo.on(events.onPlayerEnter, function (data) {
    var eve = 'onPlayerEnter';
    var msg = `playerId: ${data.playerId}, name:  ${data.name}, coin:  ${data.coin}, roundCount:  ${data.roundCount}, score:  ${data.score}`;
    bold(eve, msg);
    gameOperate.addMsg('广播：游戏' + gameId + '：用户' + data.playerId + '进入游戏！');
    gameOperate.roomData[data.playerId] = { playerId: data.playerId, coin: data.coin, name: data.name, roundCount: data.roundCount, score: data.score };
    log('广播: ', gameOperate.roomData);
});

pomelo.on(events.onPlayerLeave, function (data) {
    var eve = 'onPlayerLeave';
    var msg = `playerId: ${data.playerId}`;
    bold(eve, msg);
    gameOperate.addMsg('广播：游戏' + gameId + '：用户' + data.playerId + '退出游戏！');
    delete gameOperate.roomData[data.playerId];
});

pomelo.on(events.onKick, function (data) {
    var eve = 'onKick';
    var msg = `data: ${data}`;
    bold(eve, msg);
    gameOperate.addMsg('广播：游戏' + gameId + '：onKick ' + JSON.stringify(data));
});

pomelo.on(events.onGameFree, function (data) {
    var eve = 'onGameFree';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：进入空闲时间！');
});

pomelo.on(events.onGameStart, function (data) {
    var eve = 'onGameStart';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：进入开始时间！');
    
});

pomelo.on(events.onGameXiaZhu, function (data) {
    var eve = 'onGameXiaZhu';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：可以下注了！');
    
});

pomelo.on(events.onGameKaiPai, function (data) {
    var eve = 'onGameKaiPai';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：进入开牌时间！');
    
});


pomelo.on(events.onGameBid, function (data) {
    var msg = `事件<onGameBid>: playerId: ${data.playerId}`;
    log(msg, data);
    gameOperate.addMsg('广播：游戏' + gameId + '：有人下注！' + JSON.stringify(data));
});

pomelo.on(events.onGameOver, function (data) {
    var eve = 'onGameOver';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：开牌！！！' + JSON.stringify(data));
});

pomelo.on(events.onCalcResult, function (data) {
    var eve = 'onGameOver';
    var msg = `cbTimeLeave: ${data.cbTimeLeave}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
    gameOperate.addMsg('广播：游戏' + gameId + '：结算数据！' + JSON.stringify(data));
    // data = { "1004": { "playerId": "1004", "taxCoin": 10, "coinChange": 490, "coin": 3006719 } };

    for (let playerId in data) {
        if (gameOperate.roomData[playerId]) {
            gameOperate.roomData[playerId].coin = data[playerId].coin;
        }
    }

    if (gameOperate.bankerId) {
        gameOperate.bankerInfo = '庄:' + gameOperate.bankerId + ' coin: ' + data[gameOperate.bankerId].coin;
    }
});

pomelo.on(events.onCancelBanker, function (data) {
    var msg = `事件<onCancelBanker>: playerId: ${data.playerId}`;
    log(msg, data);
});

pomelo.on(events.onSetBanker, function (data) {
    var msg = `事件<onSetBanker>: playerId: ${data.bankerId}`;
    log(msg, data);
    var bankerId = data.bankerId;
    if (bankerId) {
        gameOperate.bankerId = bankerId;        
    }
    var player = gameOperate.roomData[bankerId];

    gameOperate.addMsg('广播：游戏' + gameId + '：用户' + bankerId + '上庄成功！');
    gameOperate.bankerInfo = '庄:' + bankerId + ' coin: ' + player.coin;
});

// console.log('%c123', 'font-weight: bold');
// bold(123);